package pers.cz.chat;

import pers.cz.chat.constants.JefClolorEnum;
import pers.cz.chat.utils.LogUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.*;
import java.nio.charset.StandardCharsets;

public class CmdInJFrame {
    private static PrintWriter printWriter;
    private static TrayIcon trayIcon;
    private static boolean isFlashing = false;

    private static final String NORMAL_ICON_PATH = "D:\\Java\\JavaSource\\Jef-Chat\\chat-client\\src\\test\\resources\\002-cyprus.png"; // 设置为你的正常图标路径
    private static final String EMPTY_ICON_PATH = "D:\\Java\\JavaSource\\Jef-Chat\\chat-client\\src\\test\\resources\\015-el-salvador.png"; // 设置为你的透明图标路径

    public static void main(String[] args) {
        // 设置系统托盘图标
        if (!SystemTray.isSupported()) {
            LogUtils.print(JefClolorEnum.YELLOW,"System tray is not supported!");
            return;
        }

        // 创建系统托盘图标
        createTrayIcon();

        // 创建 JFrame
        JFrame frame = new JFrame("CMD in JFrame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        ImageIcon icon = new ImageIcon(NORMAL_ICON_PATH);//图片相对路径
        frame.setIconImage(icon.getImage());
        frame.setSize(800, 600);

        // 创建 JTextArea 用于显示 CMD 输出
        JTextArea textArea = new JTextArea();
        textArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(textArea);
        frame.add(scrollPane, BorderLayout.CENTER);

        // 创建输入框
        JTextField textField = new JTextField();
        frame.add(textField, BorderLayout.SOUTH);

        // 启动 CMD 进程
        startCmdProcess(textArea);

        // 处理用户输入
        textField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String command = textField.getText();
                if (!command.trim().isEmpty()) {
                    executeCommand(command);
                    textField.setText(""); // 清空输入框
                }
            }
        });

        // 显示窗口
        frame.setVisible(true);

        frame.addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent e) {
                System.exit(0);
            }
        });

        // 激活闪烁线程

    }


    private static void startCmdProcess(JTextArea textArea) {
        try {
            ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/K", "chcp 65001");
            processBuilder.redirectErrorStream(true);
            Process process = processBuilder.start();

            printWriter = new PrintWriter(new OutputStreamWriter(process.getOutputStream(), StandardCharsets.UTF_8), true);

            new Thread(() -> {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        textArea.append(line + "\n");
                        textArea.setCaretPosition(textArea.getDocument().getLength());
                        triggerTrayFlashing(); // 每次读取新行时触发托盘闪烁
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void executeCommand(String command) {
        if (printWriter != null) {
            printWriter.println(command);
        }
    }

    private static void createTrayIcon() {
        Image normalImage = Toolkit.getDefaultToolkit().getImage(NORMAL_ICON_PATH); // 正常图标
        Image emptyImage = Toolkit.getDefaultToolkit().getImage(EMPTY_ICON_PATH); // 空白/透明图标
        trayIcon = new TrayIcon(normalImage, "CMD Tray");
        trayIcon.setImageAutoSize(true);

        trayIcon.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON1) {
                    JOptionPane.showMessageDialog(null, "应用程序正在运行...");
                }
            }
        });

        try {
            SystemTray.getSystemTray().add(trayIcon);
        } catch (AWTException e) {
            LogUtils.print(JefClolorEnum.YELLOW,"TrayIcon could not be added.");
        }
    }

    private static void triggerTrayFlashing() {
        if (trayIcon != null && !isFlashing) {
            isFlashing = true;
            new Thread(() -> {
                for (int i = 0; i < 5; i++) {
                    trayIcon.setImage(Toolkit.getDefaultToolkit().getImage(EMPTY_ICON_PATH)); // 设置为空图标
                    try { Thread.sleep(500); } catch (InterruptedException ignored) {}
                    trayIcon.setImage(Toolkit.getDefaultToolkit().getImage(NORMAL_ICON_PATH)); // 设置为正常图标
                    try { Thread.sleep(500); } catch (InterruptedException ignored) {}
                }
                isFlashing = false;
            }).start();
        }
    }
}
